import os
import json
from datetime import datetime
from git_utils import get_git_logs, analyze_commit
from java_parser import parse_java_file
from file_writer import output_changes_to_file

def load_config(config_path):
    with open(config_path, 'r', encoding='utf-8') as file:
        return json.load(file)

def get_monthly_api_changes(repo_path, year, month, annotations):
    # 保存当前工作目录
    original_cwd = os.getcwd()
    os.chdir(repo_path)

    start_date = datetime(year, month, 1)
    if month == 12:
        end_date = datetime(year + 1, 1, 1)
    else:
        end_date = datetime(year, month + 1, 1)

    commit_entries = get_git_logs(start_date, end_date)
    all_changes = []

    for commit_entry in commit_entries:
        commit_hash, files = analyze_commit(commit_entry)
        for file in files:
            if os.path.exists(file):
                changes = parse_java_file(file, annotations)
                all_changes.extend(changes)

    # 恢复原始工作目录
    os.chdir(original_cwd)
    return set(all_changes)  # 去重

if __name__ == '__main__':
    config_path = os.path.join(os.path.dirname(__file__), '../config/config.json')
    config = load_config(config_path)
    
    repo_path = config['repo_path']
    year = config['year']
    month = config['month']
    annotations = config['annotations']
    
    changes = get_monthly_api_changes(repo_path, year, month, annotations)
    output_changes_to_file(changes, f'api_changes_{year}_{month}.txt')
